﻿using Common.Contract.Authentication.Record;
using Common.Contract.ProductHandbook.Record;
using Common.Contract.SystemConfig.Record;
using CrossSelling.Core.Data;
using CrossSelling.Model.Interface;
using CrossSelling.Model.Model;
using System;
using System.Collections.Generic;
using System.Linq;

namespace CrossSelling.Provider
{
    public class ProductHandbookProvider : GenericProvider, IProductHandbookProvider
    {
        public List<ProductHandbookProduct> RetrieveProductHandbookCategory()
        {
            var data = repository.DbContext as CrossSellingEntities;
            var query = from x in data.ProductHandbookProducts
                        where x.ProductStatus == 1 && x.ProductType == 1
                        select x;
            return query.ToList();
        }

        public List<ProductCategory> RetrieveListCategory()
        {
            var data = repository.DbContext as CrossSellingEntities;
            var query = from x in data.ProductCategorys
                        where x.CategoryStatus == 1
                        select x;
            return query.ToList();
        }
        public CheckListDocument RetrieveChecklistDocumentByDocId(int docId)
        {
            var data = repository.DbContext as CrossSellingEntities;
            var query = from x in data.CheckListDocuments
                        where x.ChecklistDocId == docId
                        select x;
            return query.FirstOrDefault();
        }
        public List<ProductHandbookProduct> RetrieveProductProgramHandbookCategory()
        {
            var data = repository.DbContext as CrossSellingEntities;
            var query = from x in data.ProductHandbookProducts
                        where (x.ProductStatus == 1 || x.ProductStatus == 2) && x.ProductType == 2
                        select x;
            return query.ToList();
        }
        public ChecklistSubProduct RetrieveSubProductById(int subProductId)
        {
            var data = repository.DbContext as CrossSellingEntities;
            var query = from x in data.ChecklistSubProducts
                        where x.SubProductId == subProductId
                        select x;
            return query.FirstOrDefault();
        }
        public ProductHandbookProductDetail RetrieveProductHandbookProductDetail(int productId)
        {
            var data = repository.DbContext as CrossSellingEntities;
            var query = from x in data.ProductHandbookProductDetails
                        where x.ProductId == productId
                        select x;
            return query.FirstOrDefault();
        }
        public List<ProductHandbookProductDetail> RetrieveListProductDetail()
        {
            var data = repository.DbContext as CrossSellingEntities;
            var query = from x in data.ProductHandbookProductDetails
                        select x;
            return query.ToList();
        }
        public ProductHandbookProduct RetrieveProductByProductId(int productId)
        {
            var data = repository.DbContext as CrossSellingEntities;
            var query = from x in data.ProductHandbookProducts
                        where x.ProductId == productId
                        select x;
            return query.FirstOrDefault();
        }
        public List<ChecklistQuestion> RetrieveListQuestionChecklist(out int totalRecord, int product, UserRecord dao, FilterRecord textSearch = null, string lang = null, int pagesize = 0, int pageindex = 0)
        {
            var data = repository.DbContext as CrossSellingEntities;
            var toDay = DateTime.Now;
            var query = from x in data.ChecklistQuestions
                        where x.ProductId == product
                        select x;
            totalRecord = query.Count();
            return query.ToList();
        }

        public List<CheckListDocument> CheckListDocument(int product)
        {
            var data = repository.DbContext as CrossSellingEntities;
            var query = from x in data.CheckListDocuments
                        where x.ProductId == product
                        select x;
            return query.ToList();
        }

        public List<ChecklistCustomer> RetrieveListCustomerChecklist(out int totalRecord, int product, UserRecord dao, FilterRecord textSearch = null, string lang = null, int pagesize = 0, int pageindex = 0)
        {
            var data = repository.DbContext as CrossSellingEntities;
            var toDay = DateTime.Now;
            var query = from x in data.ChecklistCustomers
                        where x.ProductId == product
                        select x;

            switch (dao.GroupIdentifier)
            {
                case "1":
                    break;
                case "2":
                    query = query.Where(x => x.Region == dao.Zone);
                    break;
                case "3":
                    query = query.Where(x => x.Branch == dao.Branch);
                    break;
                case "4":
                    query = query.Where(x => x.Dao.ToUpper() == dao.Dao.ToUpper());
                    break;
                default:
                    break;
            }
            totalRecord = query.Count();

            query = query.OrderBy(x => new { x.Region, x.Branch, x.Dao });
            if (pagesize > 0 && pageindex >= 0)
            {
                query = query.Skip(pageindex * pagesize).Take(pagesize);
            }
            return query.ToList();
        }
        public List<ChecklistQuestionSubProductResult> RetrieveListRuleChecklist(out int totalRecord, int product, UserRecord dao, string textSearch = null, string lang = null, int pagesize = 0, int pageindex = 0)
        {
            var data = repository.DbContext as CrossSellingEntities;
            var toDay = DateTime.Now;
            var query = from x in data.ChecklistQuestionSubProductResults
                        where x.ProductId == product
                        select x;
            totalRecord = query.Count();

            query = query.OrderBy(x => new { x.AnswerGroup });
            if (pagesize > 0 && pageindex >= 0)
            {
                query = query.Skip(pageindex * pagesize).Take(pagesize);
            }
            return query.ToList();
        }
        public List<ChecklistHideDocWhenAnswer> RetrieveListHideDocChecklist(out int totalRecord, int product, UserRecord dao, string textSearch = null, string lang = null, int pagesize = 0, int pageindex = 0)
        {
            var data = repository.DbContext as CrossSellingEntities;
            var toDay = DateTime.Now;
            var query = from x in data.ChecklistHideDocWhenAnswers
                        where x.ProductId == product
                        select x;
            totalRecord = query.Count();

            query = query.OrderBy(x => new { x.ProductId });
            if (pagesize > 0 && pageindex >= 0)
            {
                query = query.Skip(pageindex * pagesize).Take(pagesize);
            }
            return query.ToList();
        }
        public ChecklistHideDocWhenAnswer RetrieveHideDocChecklistById(int id)
        {
            var data = repository.DbContext as CrossSellingEntities;
            var toDay = DateTime.Now;
            var query = from x in data.ChecklistHideDocWhenAnswers
                        where x.DocHideId == id
                        select x;
            return query.FirstOrDefault();
        }
        public List<ChecklistQuestionSubProductResult> RetrieveListRuleChecklistById(out int totalRecord, int groupId, UserRecord dao, string textSearch = null, string lang = null, int pagesize = 0, int pageindex = 0)
        {
            var data = repository.DbContext as CrossSellingEntities;
            var toDay = DateTime.Now;
            var query = from x in data.ChecklistQuestionSubProductResults
                        where x.AnswerGroup == groupId
                        select x;
            totalRecord = query.Count();

            query = query.OrderBy(x => new { x.QuestionId });
            if (pagesize > 0 && pageindex >= 0)
            {
                query = query.Skip(pageindex * pagesize).Take(pagesize);
            }
            return query.ToList();
        }
        public int RetrieveProductIdByDocumentId(int documentId, int subProductId)
        {
            var data = repository.DbContext as CrossSellingEntities;
            var toDay = DateTime.Now;
            var query = from x in data.CheckListDocuments
                        where x.ChecklistDocId == documentId && x.SubProductId == subProductId
                        select x;
            if (query.Count() > 0)
            {
                return query.FirstOrDefault().ProductId;
            }
            return 0;
        }

        public List<CheckListDocument> RetrieveListDocumentChecklist(out int totalRecord, int product, int subProductId, UserRecord dao, FilterRecord textSearch = null, string lang = null, int pagesize = 0, int pageindex = 0)
        {
            var data = repository.DbContext as CrossSellingEntities;
            var toDay = DateTime.Now;
            var query = from x in data.CheckListDocuments
                        where x.ProductId == product && x.SubProductId == subProductId
                        select x;
            totalRecord = query.Count();

            query = query.OrderBy(x => new { x.ChecklistDocId });
            return query.ToList();
        }
        public List<CheckListDocument> RetrieveListDocumentChecklist(out int totalRecord, ChecklistCustomer product, UserRecord dao, FilterRecord textSearch = null, string lang = null, int pagesize = 0, int pageindex = 0)
        {
            var data = repository.DbContext as CrossSellingEntities;
            var toDay = DateTime.Now;
            var query = from x in data.CheckListDocuments
                        where x.ProductId == product.ProductId && x.SubProductId == product.SubProductId
                        select x;
            totalRecord = query.Count();

            query = query.OrderBy(x => new { x.ChecklistDocId });
            return query.ToList();
        }

        public List<ChecklistDocumentByCustomer> RetrieveListDocumentByCcid(out int totalRecord, int ccid, UserRecord dao, FilterRecord textSearch = null, string lang = null, int pagesize = 0, int pageindex = 0)
        {
            var data = repository.DbContext as CrossSellingEntities;
            var toDay = DateTime.Now;
            var query = from x in data.ChecklistDocumentByCustomers
                        where x.Ccid == ccid
                        select x;
            int noSearch = int.Parse(textSearch.StatusAccPlan);
            if (noSearch != 2)
            {
                query = query.Where(x => x.Status == noSearch);
            }
            totalRecord = query.Count();

            query = query.OrderBy(x => new { x.DocumentId });
            return query.ToList();
        }
        public bool SaveCustomerChecklist(ChecklistCustomer record, List<ChecklistDocumentByCustomer> listRecords)
        {
            try
            {
                repository.ChecklistCustomers.Add(record);
                foreach (var item in listRecords)
                {
                    repository.ChecklistDocumentByCustomers.Add(item);
                }

                repository.UnitOfWork.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }
        public bool UpdateCustomerChecklist(ChecklistCustomer record, Dictionary<int, ChecklistDocumentByCustomer> listRecords)
        {

            try
            {
                var dataChecked = RetrieveChecklistCustomer(record.Ccid);
                if (dataChecked == null || dataChecked.Count() == 0) return false;
                var dataDocChecked = RetrieveChecklistDocumentByCustomer(record.Ccid);
                if (dataDocChecked == null || dataDocChecked.Count() == 0) return false;
                dataChecked.ToList().ForEach(x =>
                {
                    x.DateUpdate = record.DateUpdate;
                });

                dataDocChecked.ToList().ForEach(x =>
                {
                    if (x.Status == 0 && listRecords[x.DocumentId].Status == 1)
                    {
                        x.LastdateUpdate = DateTime.Now;
                    }
                    else if (listRecords[x.DocumentId].Status == 0)
                    {
                        x.LastdateUpdate = null;
                    }
                    x.Status = listRecords[x.DocumentId].Status;
                });

                repository.UnitOfWork.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }
        public IEnumerable<ChecklistCustomer> RetrieveChecklistCustomer(int ccid)
        {
            return repository.Find<ChecklistCustomer>(x => x.Ccid == ccid);
        }
        public IEnumerable<ChecklistDocumentByCustomer> RetrieveChecklistDocumentByCustomer(int ccid)
        {
            return repository.Find<ChecklistDocumentByCustomer>(x => x.Ccid == ccid);
        }

        public ChecklistCustomer RetrieveCustomerChecklistByCcid(int ccid, UserRecord dao)
        {
            var data = repository.DbContext as CrossSellingEntities;
            var toDay = DateTime.Now;
            var query = from x in data.ChecklistCustomers
                        where x.Ccid == ccid
                        select x;
            switch (dao.GroupIdentifier)
            {
                case "1":
                    break;
                case "2":
                    query = query.Where(x => x.Region == dao.Zone);
                    break;
                case "3":
                    query = query.Where(x => x.Branch == dao.Branch);
                    break;
                case "4":
                    query = query.Where(x => x.Dao.ToUpper() == dao.Dao.ToUpper());
                    break;
                default:
                    break;
            }
            return query.Count() > 0 ? query.FirstOrDefault() : new ChecklistCustomer();
        }
        public List<ChecklistQuestionSubProductResult> RetrieveListChecklistSample(int productId)
        {
            var data = repository.DbContext as CrossSellingEntities;
            var query = from x in data.ChecklistQuestionSubProductResults
                        where x.ProductId == productId
                        select x;
            return query.ToList();
        }
        public List<ChecklistSubProduct> RetrieveSubProductWithoutSubId(int productId, int subId = 0)
        {
            var data = repository.DbContext as CrossSellingEntities;
            var query = from x in data.ChecklistSubProducts
                        where x.ProductId == productId
                        select x;
            if (subId != 0)
            {
                query = query.Where(x => x.SubProductId != subId);
            }
            return query.ToList();
        }
        public List<ChecklistHideDocWhenAnswer> RetrieveListDocHide(int subProductId)
        {
            var data = repository.DbContext as CrossSellingEntities;
            var query = from x in data.ChecklistHideDocWhenAnswers
                        where x.SubProductId == subProductId
                        select x;
            return query.ToList();
        }
        public bool UpdateQuestionChecklist(ChecklistQuestion record)
        {
            try
            {
                var dataChecked = RetrieveChecklistQuestion(record.QuestionId);
                if (dataChecked == null || dataChecked.Count() == 0) return false;
                dataChecked.ToList().ForEach(x =>
                {
                    x.Title = record.Title;
                    x.TitleEn = record.TitleEn;
                });

                repository.UnitOfWork.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }
        public bool AddChecklistSubProduct(List<ChecklistSubProduct> listRecord)
        {
            try
            {
                int subID = repository.Find<ChecklistSubProduct>(x => true).ToList().Max(x => x.SubProductId);
                listRecord.ForEach(x =>
                {
                    subID = subID + 1;
                    x.SubProductId = subID;
                    repository.ChecklistSubProducts.Add(x);
                });
                repository.UnitOfWork.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }
        public bool UpdateProductHandbookDetail(ProductHandbookProductDetailRecord record)
        {
            try
            {
                IEnumerable<ProductHandbookProductDetail> check = repository.Find<ProductHandbookProductDetail>(x => x.ProductId == record.ProductId);
                if (check != null && check.Count() > 0)
                {
                    check.ToList().ForEach(x =>
                {
                    x.ProductName = record.ProductName;
                    x.ProductNameEn = record.ProductNameEn;
                    x.ConditionProduct = record.Condition;
                    x.ConditionProductEn = record.ConditionEn;
                    x.DocumentProduct = record.Document;
                    x.DocumentProductEn = record.DocumentEn;
                    x.OverviewProduct = record.Overview;
                    x.OverviewProductEn = record.OverviewEn;
                    x.XSellingProduct = record.Xselling;
                    x.XSellingProductEn = record.XsellingEn;
                });
                    repository.UnitOfWork.SaveChanges();
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }
        public bool UpdateRuleChecklist(List<ChecklistQuestionSubProductResult> records, int ruleId, int productId, int subId)
        {
            try
            {
                var dataChecked = RetrieveChecklistRule(productId, ruleId, subId);
                if (dataChecked == null || dataChecked.Count() == 0)
                {
                    //return false;
                }
                else
                {
                    dataChecked.ToList().ForEach(x =>
                        {
                            repository.ChecklistQuestionSubProductResults.Remove(x);
                        }
                    );
                }
                if (records.Count > 0)
                {
                    records.ForEach(x =>
                    {
                        repository.ChecklistQuestionSubProductResults.Add(x);
                    });

                }
                repository.UnitOfWork.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }
        public bool UpdateRuleHideDocChecklist(ChecklistHideDocWhenAnswer record)
        {

            try
            {
                var dataChecked = RetrieveChecklistRuleHideDoc(record.ProductId, record.DocHideId, record.SubProductId);
                if (dataChecked == null || dataChecked.Count() == 0)
                {
                    return false;
                }
                else
                {
                    dataChecked.ToList().ForEach(x =>
                    {
                        x.QuestionId = record.QuestionId;
                        x.Answer = record.Answer;
                        x.DocumentId = record.DocumentId;
                    }
                    );
                }
                repository.UnitOfWork.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }
        public bool SaveQuestionChecklist(ChecklistQuestion record)
        {
            try
            {
                repository.ChecklistQuestions.Add(record);
                repository.UnitOfWork.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }
        public bool SaveDocumentChecklist(CheckListDocument record)
        {
            try
            {
                repository.CheckListDocuments.Add(record);
                repository.UnitOfWork.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }
        public bool AddProductDetail(ProductHandbookProductDetail record)
        {
            try
            {
                repository.ProductHandbookProductDetails.Add(record);
                repository.UnitOfWork.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }
        public bool CheckRuleHideDocByParamsFromView(ChecklistHideDocWhenAnswer record)
        {
            var dataChecked = repository.Find<ChecklistHideDocWhenAnswer>(x => x.ProductId == record.ProductId && x.DocHideId == record.DocHideId).FirstOrDefault();
            return dataChecked != null && dataChecked.SubProductId == record.SubProductId;
        }
        public bool AddRuleHideDocChecklist(ChecklistHideDocWhenAnswer record)
        {
            var check = repository.Find<ChecklistHideDocWhenAnswer>(x => x.QuestionId == record.QuestionId && x.Answer == record.Answer && x.SubProductId == record.SubProductId);
            if (check != null && check.Count() != 0)
            {
                return false;
            }
            repository.ChecklistHideDocWhenAnswers.Add(record);
            repository.UnitOfWork.SaveChanges();
            return true;
        }
        public bool SaveProductHandbookProductByProductID(ProductHandbookProduct record)
        {
            try
            {
                var dataChecked = RetrieveProductByProductID(record.ProductId);
                if (dataChecked == null || dataChecked.ProductId == 0) return false;
                dataChecked.ProductStatus = record.ProductStatus;
                repository.UnitOfWork.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }
        public bool UpdateDocumentChecklist(CheckListDocument record)
        {
            try
            {
                var dataChecked = RetrieveChecklistDocument(record.ChecklistDocId);
                if (dataChecked == null || dataChecked.Count() == 0) return false;
                dataChecked.ToList().ForEach(x =>
                {
                    x.Document = record.Document;
                    x.Note = record.Note;
                    x.PictureDocument = record.PictureDocument;
                    x.Copy = record.Copy;
                    x.Original = record.Original;
                    x.Duplicate = record.Duplicate;
                });

                repository.UnitOfWork.SaveChanges();
                return true;
            }
            catch
            {
                return false;
            }
        }
        private ProductHandbookProduct RetrieveProductByProductID(int productId)
        {
            return repository.Find<ProductHandbookProduct>(x => x.ProductId == productId).FirstOrDefault();
        }
        private IEnumerable<ChecklistQuestionSubProductResult> RetrieveChecklistRule(int productId, int ruleId, int subId)
        {
            return repository.Find<ChecklistQuestionSubProductResult>(x => x.ProductId == productId && x.AnswerGroup == ruleId && x.SubProductId == subId);
        }
        private IEnumerable<ChecklistHideDocWhenAnswer> RetrieveChecklistRuleHideDoc(int productId, int ruleId, int subId)
        {
            return repository.Find<ChecklistHideDocWhenAnswer>(x => x.ProductId == productId && x.DocHideId == ruleId && x.SubProductId == subId);
        }
        private IEnumerable<ChecklistQuestion> RetrieveChecklistQuestion(int questionId)
        {
            return repository.Find<ChecklistQuestion>(x => x.QuestionId == questionId);
        }
        private IEnumerable<CheckListDocument> RetrieveChecklistDocument(int docId)
        {
            return repository.Find<CheckListDocument>(x => x.ChecklistDocId == docId);
        }
        #region Sale contest

        public List<SaleContestProgram> RetrieveAllSaleContestProgram(UserRecord dao)
        {
            var data = repository.DbContext as CrossSellingEntities;
            var query = from x in data.SaleContestPrograms
                        select x;
            return query.ToList();
        }
        public SaleContestProgramInfo RetrieveSaleContestInfoBySaleContestId(int saleContestId)
        {
            var data = repository.DbContext as CrossSellingEntities;
            var query = from x in data.SaleContestProgramInfos
                        where x.SaleContestId == saleContestId
                        select x;
            return query.FirstOrDefault();
        }
        #endregion
    }
}